<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>历史消息加载测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .session-list {
            border: 1px solid #ccc;
            padding: 10px;
            border-radius: 5px;
        }
        .message-list {
            border: 1px solid #ccc;
            padding: 10px;
            border-radius: 5px;
            max-height: 400px;
            overflow-y: auto;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #e3f2fd;
            text-align: right;
        }
        .assistant-message {
            background-color: #f5f5f5;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>历史消息加载测试</h1>
        
        <div>
            <h2>会话列表</h2>
            <div id="session-list" class="session-list">
                <div class="loading">加载中...</div>
            </div>
        </div>
        
        <div>
            <h2>消息列表</h2>
            <div id="message-list" class="message-list">
                <div class="loading">请选择一个会话</div>
            </div>
        </div>
        
        <div>
            <button id="refresh-btn">刷新会话列表</button>
        </div>
        
        <div id="error-container" class="error"></div>
    </div>

    <script>
        const API_BASE_URL = 'http://127.0.0.1:8001/v1';
        
        // 获取DOM元素
        const sessionListEl = document.getElementById('session-list');
        const messageListEl = document.getElementById('message-list');
        const errorContainerEl = document.getElementById('error-container');
        const refreshBtnEl = document.getElementById('refresh-btn');
        
        // 显示错误信息
        function showError(message) {
            errorContainerEl.textContent = message;
            setTimeout(() => {
                errorContainerEl.textContent = '';
            }, 5000);
        }
        
        // 获取会话列表
        async function loadSessions() {
            try {
                sessionListEl.innerHTML = '<div class="loading">加载中...</div>';
                const response = await fetch(`${API_BASE_URL}/sessions`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('会话列表数据:', data);
                
                if (data.items && data.items.length > 0) {
                    sessionListEl.innerHTML = '';
                    data.items.forEach(session => {
                        const sessionEl = document.createElement('div');
                        sessionEl.style.cursor = 'pointer';
                        sessionEl.style.padding = '8px';
                        sessionEl.style.borderRadius = '4px';
                        sessionEl.style.marginBottom = '5px';
                        sessionEl.style.backgroundColor = '#f0f0f0';
                        
                        sessionEl.innerHTML = `
                            <div><strong>ID:</strong> ${session.id}</div>
                            <div><strong>标题:</strong> ${session.title || '无标题'}</div>
                            <div><strong>消息数:</strong> ${session.message_count || 0}</div>
                            <div><strong>创建时间:</strong> ${new Date(session.created_at).toLocaleString()}</div>
                        `;
                        
                        sessionEl.addEventListener('click', () => loadMessages(session.id));
                        sessionEl.addEventListener('mouseover', () => {
                            sessionEl.style.backgroundColor = '#e0e0e0';
                        });
                        sessionEl.addEventListener('mouseout', () => {
                            sessionEl.style.backgroundColor = '#f0f0f0';
                        });
                        
                        sessionListEl.appendChild(sessionEl);
                    });
                } else {
                    sessionListEl.innerHTML = '<div>没有找到会话</div>';
                }
            } catch (error) {
                console.error('加载会话列表失败:', error);
                showError(`加载会话列表失败: ${error.message}`);
                sessionListEl.innerHTML = '<div>加载失败</div>';
            }
        }
        
        // 获取指定会话的消息
        async function loadMessages(sessionId) {
            try {
                messageListEl.innerHTML = '<div class="loading">加载消息中...</div>';
                const response = await fetch(`${API_BASE_URL}/sessions/${sessionId}/messages`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('消息列表数据:', data);
                
                if (data.items && data.items.length > 0) {
                    messageListEl.innerHTML = '';
                    data.items.forEach(message => {
                        const messageEl = document.createElement('div');
                        messageEl.className = `message ${message.role}-message`;
                        
                        const content = message.content || '';
                        const createdAt = new Date(message.created_at).toLocaleString();
                        
                        messageEl.innerHTML = `
                            <div><strong>${message.role === 'user' ? '用户' : 'AI助手'}:</strong> ${content}</div>
                            <div style="font-size: 0.8em; color: #666;">${createdAt}</div>
                        `;
                        
                        messageListEl.appendChild(messageEl);
                    });
                } else {
                    messageListEl.innerHTML = '<div>该会话没有消息</div>';
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                showError(`加载消息失败: ${error.message}`);
                messageListEl.innerHTML = '<div>加载失败</div>';
            }
        }
        
        // 刷新按钮点击事件
        refreshBtnEl.addEventListener('click', loadSessions);
        
        // 页面加载时获取会话列表
        loadSessions();
    </script>
</body>
</html>